/**
 * Copyright (c) 2016 coderyuan.com, Inc. All Rights Reserved.
 *
 * WebApiKit
 *
 * HibernateAbstractDao.java created on 下午3:14
 *
 * @author yuanguozheng
 * @version 1.0.0
 * @since 16/7/8
 */
package com.coderyuan.web.api.kit.database;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.List;

import javax.annotation.Resource;

/**
 * HibernateAbstractDao
 *
 * @author yuanguozheng
 */
public abstract class HibernateAbstractDao {

    @Resource
    private SessionFactory mSessionFactory;

    abstract Query makeQuery(Session session);

    private List queryList(Query query){
        return query.list();
    }

    private void executeObject() {
        Session session = mSessionFactory.openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = makeQuery(session);
            queryList(query);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (transaction != null) {
                transaction.rollback();
            }
        } finally {
            try {
                session.close();
            } catch (HibernateException e) {
                e.printStackTrace();
            }
        }
    }

}
